import React, { Component, PropTypes } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import { createForm } from 'rc-form';
import cx from 'classnames';
import { WingBlank, WhiteSpace, Flex, List, Button } from 'antd-mobile';
import { SCALE_HYP_MAP, SCALE_HYP, SCALE_HYP_ITEM } from 'const';
import styles from '../scale/styles.less';

function ScaleHypDetailTemplate({ dispatch, location, form, questions, scalevalue, ...rest }) {

  const { state, query } = location;
  const { getFieldProps, getFieldValue, setFieldsValue, validateFields } = form;

  const { step, ...restState } = state;

  if (!questions || questions.length !== SCALE_HYP.length) {
    questions = SCALE_HYP;
  }

  const title = questions[step].title;
  const menus = questions[step].menu;

  if (!Object.keys(scalevalue).length) {
    scalevalue = [[], [], [], []];
    dispatch({ type: 'scale/save', payload: { scalevalue } });
  
  }

  let normal = scalevalue[0] || []; //一般症状
  let main = scalevalue[1] || []; //主症
  let tp = scalevalue[2] || []; //舌脉症状
  let canNotSelect = scalevalue[3] || []; //不可选症状
  

  function handleChange({ target: { type, name, value, id } }) {
    if (Array.from(canNotSelect).find(item => item === id)) {
      return;
    }

    if (Array.from(normal).find(item => item.id === id)) {
      setFieldsValue({ [name]: id }); //form实际值与状态不符，用赋值保持相符
      normal = Array.from(normal).filter(item => item.id !== id); //从normal中去除
    }
    if (Array.from(main).find(item => item.id === id)) {
      setFieldsValue({ [name]: id }); //form实际值与状态不符，用赋值保持相符
      main = Array.from(main).filter(item => item.id !== id); //从main中去除
    }
    if (Array.from(tp).find(item => item.id === id)) {
      setFieldsValue({ [name]: id }); //form实际值与状态不符，用赋值保持相符
      tp = Array.from(tp).filter(item => item.id !== id); //从tp中去除
    }
    if (getFieldValue(name) === id) {
     
      setFieldsValue({ [name]: null });

      const items = SCALE_HYP_MAP[id];
   
      if (items) {
        items.split(';').forEach((item, i) => {
          if (canNotSelect.find(one => one === item)) {
            canNotSelect = canNotSelect.filter(one => one !== item);
        
          }
        });

        // 解决多症状重复互斥时会取消互斥的问题
        Array.from(normal).forEach((item, i) => {
          const items = SCALE_HYP_MAP[item];
          if (items) {
            items.split(';').forEach((item, i) => {
              if (!canNotSelect.find(one => one === item)) {
                canNotSelect.push(item);
              }
            });
          }
        });
        Array.from(main).forEach((item, i) => {
          const items = SCALE_HYP_MAP[item];
          if (items) {
            items.split(';').forEach((item, i) => {
              if (!canNotSelect.find(one => one === item)) {
                canNotSelect.push(item);
              }
            });
          }
        });
        Array.from(tp).forEach((item, i) => {
          const items = SCALE_HYP_MAP[item];
          if (items) {
            items.split(';').forEach((item, i) => {
              if (!canNotSelect.find(one => one === item)) {
                canNotSelect.push(item);
              }
            });
          }
        });
        validateFields((err, values) => {
          Object.keys(values).forEach((key) => {
            if (values[key]) {
              const items = SCALE_HYP_MAP[key];
              if (items) {
                items.split(';').forEach((item, i) => {
                  if (!canNotSelect.find(one => one === item)) {
                    canNotSelect.push(item);
                  }
                });
              }
            }
          });
        });
      }
    } else {
     
      setFieldsValue({ [name]: id });
      const items = SCALE_HYP_MAP[id];
    
      if (items) {
        items.split(';').forEach((item, i) => {
          if (!canNotSelect.find(one => one === item)) {
            canNotSelect.push(item);
         
          }
        });
      }
    }

    dispatch({ type: 'scale/save', payload: { scalevalue: [normal, main, tp, canNotSelect] } });
  }

  function validateForm() {
   

    const normal = scalevalue[0]; //一般症状
    const main = scalevalue[1]; //主症
    const tp = scalevalue[2]; //舌脉症状

    validateFields((err, values) => {
      Object.keys(values).forEach((key) => {
        if (values[key]) {
          // if (step + 1 === 9) {
          //   //舌脉症状
          //   tp.push({id:values[key],title:key});
          // } else {
            normal.push({id:values[key],title:key});
            // 改变push一般症状和主要症状时候传的是id和title 之前是只是把选项的title push进去
          // }
        }
      });
    });

    dispatch({ type: 'scale/save', payload: { scalevalue: [normal, main, tp, canNotSelect] } });
  }

  function nextHandler() {
    document.body.scrollTop = document.documentElement.scrollTop = 0;
    validateForm();

    if (step < 9) {
      let pathname = location.pathname;
      dispatch(
        routerRedux.replace({
          pathname,
          state: {
            step: step + 1,
            ...restState,
          },
        }),
      );
    } else {

      let pathname = location.pathname;
      pathname = location.pathname.replace('/detail', '/bzfx');
      dispatch(
        routerRedux.replace({
          pathname,
          state: {
            step: step + 1,
            ...restState,
          },
        }),
      );
    }
  }

  function prevHandler() {
    validateForm();
    document.body.scrollTop = document.documentElement.scrollTop = 0;
    if (step > 0) {
      let pathname = location.pathname;
      dispatch(
        routerRedux.replace({
          pathname,
          state: {
            step: step - 1,
            ...restState,
          },
        }),
      );
    }
  }

  function isActive(key, value, i, id) {
    // 选中状态下的颜色
    if (Array.from(normal).find(item => item.id === id)) {
      return true;
    }
    if (Array.from(main).find(item => item.id === id)) {
      return true;
    }
    if (Array.from(tp).find(item => item.id === id)) {
      return true;
    }

    if (!getFieldValue(key)) {
      return false;
    }

    return getFieldValue(key) === id;
  }

  function isDisable(key, value, i, id) {
    // 选中状态下的互斥项的颜色
    if (Array.from(canNotSelect).find(item => item === id)) {
      return true;
    }

    return false;
  }

  return menus
    ? <WingBlank size="md">
      <WhiteSpace />
      <List>
          <List.Item>
            <Flex justify="center">{`${step + 1}/10 ${title}`}</Flex>
            <Flex justify="center" style={{fontSize: '0.25rem',marginTop: '0.1rem'}}>在近3个月内您是否频繁出现以下症状</Flex>
            <Flex justify="center" style={{fontSize: '0.25rem'}}>（有则选，无可不选，可以多选）</Flex>
          </List.Item>
          {menus.map((menu, i) => (
            <List.Item key={i}>
              {menu.title}
              <Flex wrap="wrap" className={styles.questionOptions}>
                {menu.item.map((item, i) => {
                  const key = item.title;
                  const value = item.title;
                  const id = item.id;
                  return (
                    <label
                      key={key}
                      className={cx(styles.questionOption, styles.questionOptionNormal, {
                        [styles.questionOptionActive]: isActive(key, value, i,id),
                        [styles.questionOptionDisable]: isDisable(key, value, i,id),
                      })}
                    >
                      <input {...getFieldProps(`${key}`)} type="checkbox" name={key} value={value} id={id} checked={isActive(key, value, i, id)} onChange={handleChange} />
                      {value}
                    </label>
                  );
                })}
              </Flex>
            </List.Item>
          ))}
          <div>
            <WhiteSpace size="xl" />
            <WingBlank>
              <Flex>
                {step === 0
                  ? null
                  : <Flex.Item>
                    <Button onClick={prevHandler}>上一页</Button>
                  </Flex.Item>}
                <Flex.Item>
                  <Button type="primary" onClick={nextHandler}>下一页</Button>
                </Flex.Item>
              </Flex>
            </WingBlank>
            <WhiteSpace size="xl" />
          </div>
        </List>
      <WhiteSpace size="xl" />
    </WingBlank>
    : null;
}

export default connect(({ scale }) => ({ ...scale }))(createForm()(ScaleHypDetailTemplate));
